#pragma once
#include <vector>
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <stdexcept>

class ThreadPool
{
public:
    explicit ThreadPool(size_t threads = 4) : stop_flag(false)
    {
        std::cout << "创建线程池，线程数: " << threads << std::endl;

        for (size_t i = 0; i < threads; ++i)
        {
            workers.emplace_back([this]
                                 {
                // 工作线程函数
                for (;;) {
                    std::function<void()> task;
                    
                    {
                        std::unique_lock<std::mutex> lock(this->queue_mutex);
                        
                        // 等待任务或停止信号
                        this->condition.wait(lock, [this] {
                            return this->stop_flag || !this->tasks.empty();
                        });
                        
                        // 如果停止且任务队列为空，退出线程
                        if (this->stop_flag && this->tasks.empty()) {
                            return;
                        }
                        
                        // 获取任务
                        task = std::move(this->tasks.front());
                        this->tasks.pop();
                    }
                    
                    // 执行任务
                    try {
                        task();
                    } catch (const std::exception& e) {
                        std::cerr << "线程池任务异常: " << e.what() << std::endl;
                    }
                } });
        }
    }

    ~ThreadPool()
    {
        stop();
    }

    template <class F, class... Args>
    auto enqueue(F &&f, Args &&...args)
        -> std::future<typename std::result_of<F(Args...)>::type>
    {

        using return_type = typename std::result_of<F(Args...)>::type;

        // 不允许在停止后添加任务
        if (stop_flag)
        {
            throw std::runtime_error("线程池已停止，无法添加新任务");
        }

        auto task = std::make_shared<std::packaged_task<return_type()>>(
            std::bind(std::forward<F>(f), std::forward<Args>(args)...));

        std::future<return_type> result = task->get_future();

        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            tasks.emplace([task]()
                          { (*task)(); });
        }

        condition.notify_one();
        return result;
    }

    void stop()
    {
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            if (stop_flag)
            {
                return; // 已经停止
            }
            stop_flag = true;
        }

        // 通知所有线程
        condition.notify_all();

        // 等待所有线程结束
        for (std::thread &worker : workers)
        {
            if (worker.joinable())
            {
                worker.join();
            }
        }

        std::cout << "线程池已停止" << std::endl;
    }

private:
    std::vector<std::thread> workers;
    std::queue<std::function<void()>> tasks;

    std::mutex queue_mutex;
    std::condition_variable condition;
    bool stop_flag;
};